﻿using OA.Infrastructure.SignalR.Abstractions;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;

namespace OA.Infrastructure.SignalR;

public class ClientProxyFactory : IClientProxyFactory
{
    private readonly IServiceProvider _serviceProvider;

    public ClientProxyFactory(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public IClientProxyFactory<THub> CreateGenericFactory<THub>() where THub : Hub
    {
        return new ClientProxyFactory<THub>(_serviceProvider);
    }
}

public class ClientProxyFactory<THub> : IClientProxyFactory<THub>
    where THub : Hub
{
    private readonly IServiceProvider _serviceProvider;

    public ClientProxyFactory(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public IClientProxy CreateAllProxy()
    {
        var ctx = GetHubContext();

        return ctx.Clients.All;
    }

    public IClientProxy CreateGroupProxy(string groupName)
    {
        var ctx = GetHubContext();

        return ctx.Clients.Group(groupName);
    }

    public IClientProxy CreateUserProxy(string account)
    {
        var ctx = GetHubContext();

        return ctx.Clients.User(account);
    }

    public IGroupManager GroupManager()
    {
        var ctx = GetHubContext();

        return ctx.Groups;
    }

    private IHubContext<THub> GetHubContext()
        => _serviceProvider.GetRequiredService<IHubContext<THub>>();
}